package com.iacrqq.sedaf.demo.sHttpServer.event.handler;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpServerConnection;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.params.DefaultedHttpParams;

import com.iacrqq.sedaf.config.Configuration;
import com.iacrqq.sedaf.demo.sHttpServer.event.HttpEvent;
import com.iacrqq.sedaf.demo.sHttpServer.event.HttpEventStateEnum;
import com.iacrqq.sedaf.event.Event;
import com.iacrqq.sedaf.event.EventDispatcher;
import com.iacrqq.sedaf.event.exception.EventHandlerException;

public class ParseEventHandler extends AbstractEventHandler
{
	private static final Log logger = LogFactory.getLog(ParseEventHandler.class);

	@Override
	public void init(Configuration config) throws Exception
	{
		super.init(config);
		System.out.println("ParseEventHandler initialized.");
	}

	@Override
	public void destroy() throws Exception
	{
		System.out.println("ParseEventHandler destroied.");
	}

	@Override
	public Event handleEvent(Event event, EventDispatcher eventDispatcher) throws EventHandlerException
	{
		HttpEvent httpEvent = (HttpEvent) event;
		HttpRequest request = null;

		try
		{
			// Keep alive, dispatched from response stage
			if(httpEvent.getHttpServerConnection() == null)
			{
				HttpServerConnection httpServerConnection = new DefaultHttpServerConnection();
				httpEvent.setHttpServerConnection(httpServerConnection);
				((DefaultHttpServerConnection) httpServerConnection).bind(httpEvent.getSocket(), this.params);
			}
			else
			{
				logger.info("Keep alive request in parse");
			}
			
			request = httpEvent.getHttpServerConnection().receiveRequestHeader();
			//logger.info(request.toString());
			httpEvent.setHttpRequest(request);

			request.setParams(new DefaultedHttpParams(request.getParams(), this.params));

			httpEvent.setState(HttpEventStateEnum.HTTP_EVENT_STATE_PARSED.value());

			return httpEvent;
		}
		catch (IOException e)
		{
			logger.error(e);
			throw new EventHandlerException(e);
		}
		catch (HttpException e)
		{
			logger.error(e);
			httpEvent.setHttpException(e);
		}

		return httpEvent;
	}

	@Override
	public Event[] handleEvents(Event[] events, EventDispatcher eventDispatcher) throws EventHandlerException
	{
		// System.out.println(new
		// StringBuilder("ParseEventHandler handle ").append(events.length).append(" events:").append(events).toString());

		return events;
	}

}
